/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.neuronrobotics.replicator.gui.android;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.neuronrobotics.replicator.gui.preview.android.PickingRay;
import com.neuronrobotics.replicator.gui.preview.android.STLPreviewViewAndroid;
import com.neuronrobotics.replicator.gui.preview.controller.STLPreviewMouseController.MouseControlMode;
import com.neuronrobotics.replicator.gui.preview.model.DefaultSTLPreviewWorkspaceModel;
import com.neuronrobotics.replicator.gui.preview.model.STLWorkspaceModel;
import com.neuronrobotics.replicator.gui.stl.STLFacet;
import com.neuronrobotics.replicator.gui.stl.STLLoader;
import com.neuronrobotics.replicator.gui.stl.STLObject;
import com.neuronrobotics.replicator.gui.stl.STLWorkspaceObject;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

public class MainActivity extends Activity implements OnMenuItemClickListener,
		OnClickListener {

	private STLPreviewViewAndroid mGLView;
	
	private File mainDir;

	private STLWorkspaceModel theModel;
	
	private boolean useTestModel = true;

	private float[] defaultCameraPositon = {100,100,100};

	private float[] defaultCameraFocus = {0,0,0};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mainDir = this.getFilesDir();
		mainDir = new File(System.getProperty("java.io.tmpdir"));
				
		Log.d("DIR",Arrays.toString(mainDir.list()));

		// Create a GLSurfaceView instance and set it
		// as the ContentView for this Activity

		if(useTestModel ) theModel = getTestModel();		
		else theModel = new DefaultSTLPreviewWorkspaceModel();

		mGLView = new STLPreviewViewAndroid(this, theModel);

		//TODO 
		ProgressBar loadView = new ProgressBar(this);
		loadView.setIndeterminate(true);
		loadView.setVisibility(View.GONE);
		loadView.setMinimumHeight(20);
		loadView.setMinimumWidth(200);
		loadView.setEnabled(true);

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				30, 40);
		params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
		params.height = RelativeLayout.LayoutParams.MATCH_PARENT;
	
		this.setContentView(mGLView, params);
		
		mGLView.getTheController().placeAllObjectsOnWorkspace();
		
		registerForContextMenu(mGLView);
				
		View buttonOverlay = View.inflate(this, R.layout.button_overlay, new LinearLayout(this));
		addContentView(buttonOverlay, params);
		
		List<View> touchables = buttonOverlay.getTouchables();
		for(View v:touchables){
			v.setOnClickListener(this);
		}
		
		this.onClick(findViewById(R.id.cam_rotate));
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mGLView.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mGLView.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_stl_add:
			// mGLView.showContextMenu();
			testAdd();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void testAdd() {

		InputStream theStream = MainActivity.class
				.getResourceAsStream("bottle.stl");

		try {
			STLObject newTestObject = STLLoader.loadFile(theStream, true);
			theModel.addSTLObject(newTestObject);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		PickingRay unused = new PickingRay();
		if(mGLView.getPick(unused)==null){
		inflater.inflate(R.menu.no_pick_context,menu);
			menu.setHeaderTitle("Options");
		menu.findItem(R.id.cameraReset).setOnMenuItemClickListener(this);
			return;
		}
		
		//menu.getItem(0).setOnMenuItemClickListener(this);
		
		menu.setHeaderTitle(mGLView.getPick(unused).getName() + " options");
		inflater.inflate(R.menu.stl_context_menu, menu);
		
		//TODO temporary while I figure this shit out
		menu.findItem(R.id.remove).setOnMenuItemClickListener(this);
		menu.findItem(R.id.duplicate).setOnMenuItemClickListener(this);
		menu.findItem(R.id.Reorient).setOnMenuItemClickListener(this);
		menu.findItem(R.id.Scale).setOnMenuItemClickListener(this);
		menu.findItem(R.id.reset).setOnMenuItemClickListener(this);
		menu.findItem(R.id.cameraReset).setOnMenuItemClickListener(this);
	
	}
	
	@Override
	public boolean onMenuItemClick(MenuItem arg0) {
		
		PickingRay unused = new PickingRay();
		
		STLObject currPick = mGLView.getPick(unused);
		
		switch(arg0.getItemId()){
		case R.id.duplicate:
			mGLView.getTheController().duplicateSTLObject(currPick);
			break;
		case R.id.remove:
			mGLView.getTheController().removeSTLObject(currPick);
			break;
		case R.id.cameraReset:
			mGLView.getTheController().getGeneralCameraController().setCamera(defaultCameraPositon, defaultCameraFocus);
			break;
		case R.id.reset: 
			mGLView.getTheController().resetCurrentModel(currPick);
			mGLView.getTheController().placeAllObjectsOnWorkspace();
			break;
		case R.id.Scale:
			mGLView.getTheController().increaseScale(currPick, 1);//TODO test only
			break;
		case R.id.Reorient:
			//TODO
			break;
		default:
			break;
		}
		
		mGLView.clearPick();
		
		return true;
	}

	@Override
	public void onClick(View arg0) {
		MouseControlMode currentSelectedMouseMode = MouseControlMode.CAMERA_ROTATE;

		((ImageButton) findViewById(R.id.cam_rotate))
				.setBackgroundColor(Color.GRAY);
		((ImageButton) findViewById(R.id.model_rotate))
				.setBackgroundColor(Color.GRAY);
		((ImageButton) findViewById(R.id.model_translate))
				.setBackgroundColor(Color.GRAY);
		((ImageButton) findViewById(R.id.model_scale))
				.setBackgroundColor(Color.GRAY);
		((ImageButton) findViewById(R.id.model_reorient))
				.setBackgroundColor(Color.GRAY);

		if (arg0.getId() == R.id.cam_rotate) {
			currentSelectedMouseMode = MouseControlMode.CAMERA_ROTATE;
			((ImageButton) findViewById(R.id.cam_rotate))
					.setBackgroundColor(Color.BLUE);
		} else if (arg0.getId() == R.id.model_rotate) {
			currentSelectedMouseMode = MouseControlMode.MODEL_ROTATE_Y;
			((ImageButton) findViewById(R.id.model_rotate))
					.setBackgroundColor(Color.BLUE);
		} else if (arg0.getId() == R.id.model_translate) {
			currentSelectedMouseMode = MouseControlMode.MODEL_TRANSLATE_XZ;
			((ImageButton) findViewById(R.id.model_translate))
					.setBackgroundColor(Color.BLUE);
		} else if (arg0.getId() == R.id.model_scale) {
			currentSelectedMouseMode = MouseControlMode.SCALE;
			((ImageButton) findViewById(R.id.model_scale))
					.setBackgroundColor(Color.BLUE);
		} else if (arg0.getId() == R.id.model_reorient) {
			currentSelectedMouseMode = MouseControlMode.REORIENT;
			((ImageButton) findViewById(R.id.model_reorient))
					.setBackgroundColor(Color.BLUE);
		} else	Log.d("BUTTON", "None");
		
		this.mGLView.getTheController().getSTLPreviewMouseController().setCurrentMouseControlMode(currentSelectedMouseMode);
		
	
	}
	
	private static STLWorkspaceModel getTestModel(){
		// ////////////////////////For Testing

				STLFacet stlF1 = new STLFacet(new float[] { 0, 1, 0, -1, -1, 0, 1, -1,
						0 });
				STLFacet stlF2 = new STLFacet(new float[] { 0, 1, 0, -1, -1, -1, -1,
						-1, -1 });

				ArrayList<STLFacet> facList = new ArrayList<STLFacet>();
				facList.add(stlF1);
				facList.add(stlF2);
				STLObject theSTL = new STLObject("Test", facList);
				STLObject theSTL2 = new STLObject("Test2", facList);

				STLWorkspaceObject theWSObj = new STLWorkspaceObject(theSTL);

				Log.d("MyTag", "Before try/catch");
				// testDraw = new STLObjectDrawable(theSTL);
				try {
					Log.d("MyTag", "Inside try/catch");
					
					//TODO this shit ain't workin'
					InputStream anotherSTL = MainActivity.class.getResourceAsStream("spaceinvaderBIN.stl");
					Log.d("BIN","BIN File null? "+(anotherSTL==null));
					Log.d("BIN","BIN read -1? "+(anotherSTL.read()==-1));
					
					theSTL = STLLoader.loadFile(
							MainActivity.class.getResourceAsStream("spaceinvader.stl"),
							true);
					
					

					Log.d("MyTag", "File loaded");
					// testDraw = new STLObjectDrawable(theSTL);
					// testOutline = new STLOutlineDrawable(theSTL);
					Log.d("MyTag", theSTL.getName());
					// ////////////////////
					Log.d("MyTag", "Inside try/catch");
					theSTL2 = STLLoader.loadFile(MainActivity.class
							.getResourceAsStream("tetrahedron-openface.stl"), true);

					theWSObj = new STLWorkspaceObject(STLLoader.loadFile(
							MainActivity.class
									.getResourceAsStream("testWorkspaceSTL.stl"), true));

				} catch (IOException e) {
					e.printStackTrace();
					Log.d("MyTag", "IOException dun gone happen'd");
					Log.d("MyTag", e.getMessage());
				}
				
				final STLWorkspaceModel testModel = new DefaultSTLPreviewWorkspaceModel();

				theSTL = theSTL.getTransformedSTLObject(new float[] { 1, 0, 0, 0, 0,
						1, 0, 0, 0, 0, 1, -25, 0, 0, 0, 1 });

				if(theSTL!=null)testModel.addSTLObject(theSTL);

				theSTL2 = theSTL2.getTransformedSTLObject(new float[] { 1, 0, 0, 0, 0,
						1, 0, 0, 0, 0, 1, 15, 0, 0, 0, 1 });

				testModel.addSTLObject(theSTL2);
				testModel.setWorkspace(theWSObj);
				// //////////////////////////
				Log.d("BIN","Made it here");
				return testModel;
	}

}
